package com.chima.action;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import com.chima.domain.Employees;
import com.chima.domain.MiddleEmpRate;
import com.chima.domain.PageRequestBean;
import com.chima.domain.PageResponseBean;
import com.chima.domain.Rate;
import com.chima.service.EmployeeService;
import com.chima.service.RateService;
import com.opensymphony.xwork2.ActionSupport;
import flexjson.JSONSerializer;

public class RateAction extends ActionSupport {
	
	private int start;// 开始页码
	private int limit; //每页显示
	private int page;//页数
	private boolean success=false ;
	private RateService  rateService;
	private EmployeeService  employeeService;
	private List<Rate> rates;
	
	private int [] ids;
	private Double [] grades;
	private int [] workdays;
	private String serchdate;
	private int searchdepartment;
	private List<MiddleEmpRate> middleEmpRates;
	
	public List<MiddleEmpRate> getMiddleEmpRates() {
		return middleEmpRates;
	}
	public void setMiddleEmpRates(List<MiddleEmpRate> middleEmpRates) {
		this.middleEmpRates = middleEmpRates;
	}
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}
	public int getSearchdepartment() {
		return searchdepartment;
	}
	public void setSearchdepartment(int searchdepartment) {
		this.searchdepartment = searchdepartment;
	}
	public String getSerchdate() {
		return serchdate;
	}
	public void setSerchdate(String serchdate) {
		this.serchdate = serchdate;
	}
	public Double[] getGrades() {
		return grades;
	}
	public void setGrades(Double[] grades) {
		this.grades = grades;
	}
	public int[] getIds() {
		return ids;
	}
	public void setIds(int[] ids) {
		this.ids = ids;
	}
	public void setRateService(RateService rateService) {
		this.rateService = rateService;
	}
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getLimit() {
		return limit;
	}
	public void setLimit(int limit) {
		this.limit = limit;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	public int[] getWorkdays() {
		return workdays;
	}
	public void setWorkdays(int[] workdays) {
		this.workdays = workdays;
	}
	public String  ListRate() throws Exception{
		Employees  emp =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
	    PageRequestBean pageRequestBean = new PageRequestBean();
	    DetachedCriteria criteria = DetachedCriteria.forClass(Rate.class);
	    if(serchdate==null||"".equals(serchdate)){
	    	 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
	         Calendar   calendar=Calendar.getInstance(); 
	         calendar.setTime(new Date());
	         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
	         String date= sdf.format(calendar.getTime());
	 	     criteria.add(Restrictions.eq("date",date));
	 	     pageRequestBean.setDate(date);
	    }
	   if(serchdate!=null && !"".equals(serchdate)){
		   criteria.add(Restrictions.eq("date",serchdate));
		   pageRequestBean.setDate(serchdate);
		   
	   }
	   if(!emp.getName().equals("admin")){     
		    	 criteria.add(Restrictions.eq("department.id",emp.getDepartment().getId() ));
		    	 criteria.add(Restrictions.eq("position",1 ));
		    	 pageRequestBean.setDept(emp.getDepartment().getId());
	    }else{
	    	if(searchdepartment!=0){
		    	 criteria.add(Restrictions.eq("department.id",searchdepartment ));
		    	 pageRequestBean.setDept(searchdepartment);
		     }
	    }
	    pageRequestBean.setCriteria(criteria);
		pageRequestBean.setStart(start);
		pageRequestBean.setLimit(limit);
		pageRequestBean.setPage(page);
		
		PageResponseBean pageResponseBean =rateService.findRate(pageRequestBean);
		rates=pageResponseBean.getRows();
        int total=0;
        total =pageResponseBean.getTotal();
		// 输出json内容到客户端
        JSONSerializer jsonSerializer = new JSONSerializer();
        jsonSerializer.include("*.id","*.adcontent");
        jsonSerializer.exclude("*.class");
        String resultJson1 = jsonSerializer.serialize(rates);  
        String resultJson2 =jsonSerializer.serialize(total);
        String jsonString = "{total:"+resultJson2.toString()+",rates:"+resultJson1.toString()+"}";
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(jsonString);
		return NONE;
	
  }
/**
 * 修改人员评级
 * 
 * 
 */
	public String pingji() throws Exception {
		 for(int i=0;i<ids.length;i++){
			rateService.updateGrade(grades[i], ids[i]);
		 }
	     this.success=true;
		 JSONSerializer jsonSerializer = new JSONSerializer();
	     String resultJson =jsonSerializer.serialize(success);
	     String jsonString = "{success:"+resultJson.toString()+"}";
		 ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		 ServletActionContext.getResponse().getWriter().print(jsonString);
			return NONE;   
		}
	public String editWorkDay() throws Exception {
		 for(int i=0;i<ids.length;i++){
			rateService.updateWorkDay(workdays[i], ids[i]);
		 }
	     this.success=true;
		 JSONSerializer jsonSerializer = new JSONSerializer();
	     String resultJson =jsonSerializer.serialize(success);
	     String jsonString = "{success:"+resultJson.toString()+"}";
		 ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		 ServletActionContext.getResponse().getWriter().print(jsonString);
			return NONE;   
		}

	public String InserPingeji() throws Exception {
		  Employees  emp =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
		  List<Employees> employees = null;
		  if(emp.getName().equals("admin")){
			  if(serchdate==null||"".equals(serchdate)){
				    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
			         Calendar   calendar=Calendar.getInstance(); 
			         calendar.setTime(new Date());
			         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
			         String date= sdf.format(calendar.getTime());
			         if(searchdepartment!=0){
			        	 rates=rateService.findByDateaAndDepart(date, searchdepartment);
			        	  employees= employeeService.findEmployeesByDeparmet(searchdepartment);
			         }
			         
			  }else{
				  if(searchdepartment==0){
					  rates=rateService.findByDate(serchdate);
					  employees= employeeService.findALL();
				  }else{
					  rates=rateService.findByDateaAndDepart(serchdate, searchdepartment);  
					  employees= employeeService.findEmployeesByDeparmet(searchdepartment);
				  }
				 
			  }
			 
		  }else{
				  if(serchdate==null||"".equals(serchdate)){
					  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
				         Calendar   calendar=Calendar.getInstance(); 
				         calendar.setTime(new Date());
				         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
				         String date= sdf.format(calendar.getTime());
					  rates=rateService.findByDateaAndDepart(date, emp.getDepartment().getId());
				  }else{
					  rates=rateService.findByDateaAndDepart(serchdate, emp.getDepartment().getId()); 
				  }
				
			  employees= employeeService.findEmployeesByDeparmet(emp.getDepartment().getId());
		  }
		
		  
		  if(rates.size()==0){
//			  List<Employees> employees= employeeService.findEmployeesByDeparmet(searchdepartment);
			  if(serchdate==null||"".equals(serchdate)){
				    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
			         Calendar   calendar=Calendar.getInstance(); 
			         calendar.setTime(new Date());
			         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
			         String date= sdf.format(calendar.getTime());
				  for(Employees e:employees ){
					  if (e.getDepartment().getXzorzy()==1) {
							Rate r=new Rate();
							r.setDate(date);
							r.setDepartment(e.getDepartment());
							r.setGrade(100.0);
							r.setEmployee(e);
							r.setKslx(1);
							if (e.getPosition()==10) {
							r.setFlagzuzhang(1)	;
							}
							
							r.setZuname(e.getZuname());
							r.setPosition(e.getPosition());
							r.setActualworkday(getdays());
							r.setWorkday(getdays());
							rateService.save(r);
						}else {
							Rate r=new Rate();
							r.setDate(date);
							r.setKslx(0);
							r.setZuname("不需要");
							r.setFlagzuzhang(0);
							r.setDepartment(e.getDepartment());
							r.setGrade(100.0);
							r.setEmployee(e);
							r.setPosition(e.getPosition());
							r.setActualworkday(getdays());
							r.setWorkday(getdays());
							rateService.save(r);
						}
//						Rate r=new Rate();
//						r.setDate(date);
//						r.setDepartment(e.getDepartment());
//						r.setGrade(100.0);
//						r.setPosition(e.getPosition());
//						r.setEmployee(e);
//						r.setWorkday(getdays());
//						r.setActualworkday(getdays());
//						rateService.save(r);
					}
				  }else{
					  for(Employees e:employees ){
						  if (e.getDepartment().getXzorzy()==1) {
								Rate r=new Rate();
								r.setDate(serchdate);
								r.setDepartment(e.getDepartment());
								r.setGrade(100.0);
								r.setEmployee(e);
								r.setKslx(1);
								if (e.getPosition()==10) {
								r.setFlagzuzhang(1)	;
								}
								
								r.setZuname(e.getZuname());
								r.setPosition(e.getPosition());
								r.setActualworkday(getdays());
								r.setWorkday(getdays());
								rateService.save(r);
							}else {
								Rate r=new Rate();
								r.setDate(serchdate);
								r.setKslx(0);
								r.setZuname("不需要");
								r.setFlagzuzhang(0);
								r.setDepartment(e.getDepartment());
								r.setGrade(100.0);
								r.setEmployee(e);
								r.setPosition(e.getPosition());
								r.setActualworkday(getdays());
								r.setWorkday(getdays());
								rateService.save(r);
							}
						  
//							Rate r=new Rate();
//							r.setDate(serchdate);
//							r.setDepartment(e.getDepartment());
//							r.setGrade(1.3);
//							r.setPosition(e.getPosition());
//							r.setEmployee(e);
//							r.setWorkday(getDayByYearAndMonth(serchdate));
//							r.setActualworkday(getDayByYearAndMonth(serchdate));
//							rateService.save(r);
				  }
			 }
		  }else if(rates.size()>0){
//			  List<Employees> e= employeeService.findEmployeesByDeparmet(searchdepartment);
			   	if(serchdate==null||"".equals(serchdate)){
					   	 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
				         Calendar   calendar=Calendar.getInstance(); 
				         calendar.setTime(new Date());
				         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
				         String date= sdf.format(calendar.getTime());
				         for(Employees ee:employees){
							  rateService.savaOrupdateRate(date, ee);
						  } 
			   	}else{
				   	 for(Employees ee:employees){
						  rateService.savaOrupdateRate(serchdate, ee);
					  } 
			   	}
			 
		  }
			return NONE;   
		}
/**
 * 显示中层领导评价	
 * @return
 * @throws Exception
 */
	public String  ListMiddleRate() throws Exception{
		
		Employees  emp =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
		String[] str1=emp.getDataPermission().split(",");
		Integer [] data = new Integer[str1.length];
		 for (int i = 0; i <str1.length; i++)
		 {
		   data [i] = Integer.parseInt(str1[i]);
		}
	    PageRequestBean pageRequestBean = new PageRequestBean();
	    DetachedCriteria criteria = DetachedCriteria.forClass(Rate.class);
	    if(serchdate==null||"".equals(serchdate)){
	    	 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
	         Calendar   calendar=Calendar.getInstance(); 
	         calendar.setTime(new Date());
	         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
	         String date= sdf.format(calendar.getTime());
	 	     criteria.add(Restrictions.eq("date",date));
	 	     pageRequestBean.setDate(date);
	    }
	   if(serchdate!=null && !"".equals(serchdate)){
		   criteria.add(Restrictions.eq("date",serchdate));
		   pageRequestBean.setDate(serchdate);
		   
	   }
		   
        criteria.add(Restrictions.in("department.id", data));
        criteria.add(Restrictions.eq("position",2));   	 
	    pageRequestBean.setCriteria(criteria);
		pageRequestBean.setStart(start);
		pageRequestBean.setLimit(limit);
		pageRequestBean.setPage(page);
		
		PageResponseBean pageResponseBean =rateService.findMiddleRate(pageRequestBean);
		List<MiddleEmpRate> middleEmpRates=pageResponseBean.getRows();
        int total=pageResponseBean.getTotal();
		// 输出json内容到客户端
        JSONSerializer jsonSerializer = new JSONSerializer();
        jsonSerializer.include("*.id","*.adcontent");
        jsonSerializer.exclude("*.class");
        String resultJson1 = jsonSerializer.serialize(middleEmpRates);  
        String resultJson2 =jsonSerializer.serialize(total);
        String jsonString = "{total:"+resultJson2.toString()+",middleEmpRates:"+resultJson1.toString()+"}";
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(jsonString);
		return NONE;
  }
	/**
	 * 中层考评评级
	 */
	public String Middlepingji() throws Exception {
		 for(int i=0;i<ids.length;i++){
//			rateService.updateMiddleGrade(grades[i], ids[i]);
			rateService.updateGrade(grades[i], ids[i]);
		 }
	     this.success=true;
		 JSONSerializer jsonSerializer = new JSONSerializer();
	     String resultJson =jsonSerializer.serialize(success);
	     String jsonString = "{success:"+resultJson.toString()+"}";
		 ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		 ServletActionContext.getResponse().getWriter().print(jsonString);
			return NONE;   
		}
/**
 * 	中等领导评级
 * 
 */
	public String InserMiddlePingeji() throws Exception {
		  Employees  emp =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
		  List<Employees> employees = null;
		  if(emp.getName().equals("admin")){
			  if(serchdate==null||"".equals(serchdate)){
				    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
			         Calendar   calendar=Calendar.getInstance(); 
			         calendar.setTime(new Date());
			         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
			         String date= sdf.format(calendar.getTime());
			         rates =rateService.findMiddleEmpRateByDate(date,2);
			         employees= employeeService.findEmployeesByposition(2);
			         
			         
			  }else{
				  		rates=rateService.findMiddleEmpRateByDate(serchdate,2);
			            employees= employeeService.findEmployeesByposition(2); 
			  }
			 
		  }else{
				  if(serchdate==null||"".equals(serchdate)){
					  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
				         Calendar   calendar=Calendar.getInstance(); 
				         calendar.setTime(new Date());
				         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
				         String date= sdf.format(calendar.getTime());
				         middleEmpRates=rateService.findMiddleEmpRateByDateAndDept(date, emp.getDataPermission());
				  }else{
					  middleEmpRates=rateService.findMiddleEmpRateByDateAndDept(serchdate, emp.getDataPermission());
				  }
				 
				  employees= employeeService.findMiddleEmployees(2,emp.getDataPermission());
		  }
		
		  
		  if(rates.size()==0){

			  if(serchdate==null||"".equals(serchdate)){
				    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
			         Calendar   calendar=Calendar.getInstance(); 
			         calendar.setTime(new Date());
			         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
			         String date= sdf.format(calendar.getTime());
				  for(Employees e:employees ){
					    Rate r=new Rate();
						r.setDate(date);
						r.setDepartment(e.getDepartment());
						r.setGrade(1.3);
						r.setPosition(e.getPosition());
						r.setEmployee(e);
						r.setPosition(e.getPosition());
						r.setWorkday(getdays());
						r.setActualworkday(getdays());
						rateService.save(r);
					}
				  }else{
					  for(Employees e:employees ){
						    Rate r=new Rate();
							r.setDate(serchdate);
							r.setDepartment(e.getDepartment());
							r.setGrade(1.3);
							r.setPosition(e.getPosition());
							r.setEmployee(e);
							r.setActualworkday(getDayByYearAndMonth(serchdate));
							r.setWorkday(getDayByYearAndMonth(serchdate));
							rateService.save(r);
				  }
			 }
		  }else if(rates.size()>0){
			   	if(serchdate==null||"".equals(serchdate)){
					   	 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
				         Calendar   calendar=Calendar.getInstance(); 
				         calendar.setTime(new Date());
				         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)); 
				         String date= sdf.format(calendar.getTime());
				         for(Employees ee:employees){
				        	 rateService.savaOrupdateRate(date, ee);
//							  rateService.savaOrupdateMiddleRate(date, ee);
						  } 
			   	}else{
				   	 for(Employees ee:employees){
//						  rateService.savaOrupdateMiddleRate(serchdate, ee);
						  rateService.savaOrupdateRate(serchdate, ee);
					  } 
			   	}
			 
		  }
			return NONE;   
		}
/**
 * 
 *获得本月天数
 */
	 private static int getdays(){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+1);
		cal.set(Calendar.DAY_OF_MONTH,1);
		cal.set(Calendar.DATE,cal.get(Calendar.DATE)-1);
		int days=cal.get(Calendar.DAY_OF_MONTH);
		System.out.println("当月天数:"+cal.get(Calendar.DAY_OF_MONTH));
		return days;
	}
/**
 * 根据日期获得天数
 */
	 private static int getDayByYearAndMonth(String date){
			String dyear=date.substring(0, 4);
			String dmouth=date.substring(5, 7);
		     SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy/MM");
		    Calendar rightNow = Calendar.getInstance();
		    try{
		    rightNow.setTime(simpleDate.parse(dyear+"/"+dmouth));
		    }catch(ParseException e){
		    e.printStackTrace();
		    }
		    return rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);
    }
}

